import React, { Component } from 'react';
import { getMultiLang, createPage, cardCache, toast, viewModel, promptBox, base, formDownload, output } from 'nc-lightapp-front';
import _ from 'lodash-es';
import config from './config';
import {
    onSearchButtonClick,
    onPageButtonClick,
    onTablePageChange,
    onTableInnerButtonClick,
    onTableSelectChange
} from './events';
import api from '../../common/api';
import {setForm} from 'src/erm/sscrppublic/common/utils/setComponentUsed';
import BusinessUnitTreeRef from 'uapbd/refer/org/BusinessUnitTreeRef';
import './index.less'
const { NCModal, NCButton, NCPagination } = base;
class Page extends Component {
    constructor(props) {
        super(props);
        setForm(props, "QQModel")
        props.use.form(config.headcode);
        props.use.form(config.quickcopycode);
        props.use.search(config.headcode);
        props.use.editTable(config.bodycode);
        // props.use.table(config.tradetypecode);
        this.state = {
            multiLang: {},
            isHasDelete:false ,// 是否执行过删除操作
            isHasAdd:false, // 是否执行新增操作
            isHasImport:false, // 是否执行过导入操作
            currentOrg:'' ,// 当前 pk_org
            businessUnitTreeRefValue:{}, // 参照树形结构数据
            isInitPageSize:true, // 初始化pageSize
            orgDisabled:false, // 浏览态可以切换业务单元，编辑态禁用
        };
        // TODO 缓存多语

        this.setPageStatus = this.setPageStatus.bind(this);
        this.handleImport = this.handleImport.bind(this);
        this.handleInitQuickCopy = this.handleInitQuickCopy.bind(this);
        this.handleInitImport = this.handleInitImport.bind(this);
        this.handleDelete = this.handleDelete.bind(this);
        this.handleQuickCopyBtnSure = this.handleQuickCopyBtnSure.bind(this);
        this.handleShowOrHideQuickCopyModal = this.handleShowOrHideQuickCopyModal.bind(this);
        this.handleShowQuickCopyTip = this.handleShowQuickCopyTip.bind(this);
        this.handleStartOrEndUse = this.handleStartOrEndUse.bind(this);
        this.handleExport = this.handleExport.bind(this);
        this.addTableLine = this.addTableLine.bind(this);
        this.loadData = this.loadData.bind(this);
        this.handleResetOperateStatus = this.handleResetOperateStatus.bind(this);
        this.handleShowOrHideDeleteModal = this.handleShowOrHideDeleteModal.bind(this);
        this.handleCancleBtnSure = this.handleCancleBtnSure.bind(this);
        this.handleCancle = this.handleCancle.bind(this);
        this.onBusinessUnitTreeRefChange = this.onBusinessUnitTreeRefChange.bind(this);
        this.handleHasChooseOrg = this.handleHasChooseOrg.bind(this);
    }

    tradeTypeInstance = null;

    componentDidMount() {
        this.initTempAndLang();
    }

    initTempAndLang() {
        const props = this.props;
        getMultiLang({
            ...config.multiLang,
            callback: (json) => {
                this.setState({ multiLang: json }, () => {
                    props.createUIDom({ pagecode: config.pagecode, appcode:config.appcode  }, (data) => {
                        console.log('=====template', data);
                        this.setButton(data.button);
                        this.setMeta(data.template, data.button);
                    });
                });
            }
        });
    }

    setMeta(meta, button) {
        const props = this.props;
        const that = this;
        meta[config.headcode].items.forEach((item) => {
            if (item.attrcode === 'pk_tradetypeid') {
                item.queryCondition = function () {
                    return {
                        GridRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.ErmTranstypeRefSqlBuilder'
                    };
                };
            } else if (item.attrcode === 'pk_org') {
                item.queryCondition = function () {
                    return {
                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.OrgTreeRefSqlBuilder',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                };
            } else if( item.attrcode == 'tradetype' ){//交易类型
                item.queryCondition = function () {
                    return {
                        GridRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.ErmIntellectfillTranstypeRefSqlBuilder'
                    };
                };
            } else if (item.attrcode == 'pk_dept') { //部门
                item.queryCondition = () => {
                    if( !this.handleHasChooseOrg()){
                        return
                    }
                    return {
                        // TreeRefActionExt: DeptTreeRefFilterPath,
                        GridRefActionExt:'nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder',
                        pk_org:this.state.currentOrg
                    }; // 根据apply_org过滤
                };
            }
            else if (item.attrcode == 'szxm') {//收支项目
                item.queryCondition = function () {
                    let currentData = that.props.editTable.getClickRowIndex(config.bodycode) || {}; // 获取当前选中的收支项目
                    let tradetype = _.get(currentData, 'record.values.tradetype.value','');
                    const { record = '' } = currentData
                    let crossrule_datas = {};
                    let head = {};
                    head.rows = record && [record] || [];
                    head.areaType = "table";
                    head.areacode = "table";
                    crossrule_datas.head = head;
                    // 拼接入参
                    return {
                        "isShowUnit": false,
                        "DataPowerOperationCode": "fi",
                        "isDataPowerEnable": "Y",
                        "isgrouppower": false,
                        "refpath": "uapbd/refer/fiacc/InoutBusiClassTreeRef/index",
                        //"crossrule_datas":[currentData], // 当前行数据
                        "crossrule_datas": JSON.stringify(crossrule_datas),
                        "crossrule_tradetype": tradetype,
                        "crossrule_org": that.state.currentOrg,
                        "crossrule_datatypes": "grid",
                        "crossrule_area": "table",
                        "crossrule_itemkey": "szxmid",
                        "crossrule_isHead": "false",
                        "pk_org": that.state.currentOrg,
                        "TreeRefActionExt": "nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder"
                    };
                };
            }
        });

        // 表体里筛选条件
        meta[config.bodycode].items.forEach((item) => {        
            if (item.attrcode == 'pk_dept') { //部门
                item.queryCondition = () => {
                    return {
                        // TreeRefActionExt: DeptTreeRefFilterPath,
                        GridRefActionExt:'nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder',
                        pk_org:this.state.currentOrg
                    }; // 根据apply_org过滤
                };
            }

            if( item.attrcode == 'tradetype' ){//交易类型
                item.queryCondition = function () {
                    return {
                        GridRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.ErmIntellectfillTranstypeRefSqlBuilder'
                    };
                };
            }

            if (item.attrcode == 'szxm') {//收支项目
                item.queryCondition = function () {
                    let currentData = that.props.editTable.getClickRowIndex(config.bodycode) || {}; // 获取当前选中的收支项目
                    let tradetype = _.get(currentData, 'record.values.tradetype.value','');
                    const { record = '' } = currentData
                    let crossrule_datas = {};
                    let head = {};
                    head.rows = [record];
                    head.areaType = "table";
                    head.areacode = "table";
                    crossrule_datas.head = head;
                    // 拼接入参
                    return {
                        "isShowUnit": false,
                        "DataPowerOperationCode": "fi",
                        "isDataPowerEnable": "Y",
                        "isgrouppower": false,
                        "refpath": "uapbd/refer/fiacc/InoutBusiClassTreeRef/index",
                        //"crossrule_datas":[currentData], // 当前行数据
                        "crossrule_datas": JSON.stringify(crossrule_datas),
                        "crossrule_tradetype": tradetype,
                        "crossrule_org": that.state.currentOrg,
                        "crossrule_datatypes": "grid",
                        "crossrule_area": "table",
                        "crossrule_itemkey": "szxmid",
                        "crossrule_isHead": "false",
                        "pk_org": that.state.currentOrg,
                        "TreeRefActionExt": "nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder"

                    };
                };
            }
        });


        meta[config.bodycode].pagination = true;
        meta[config.bodycode].pageInfo = {
            pageSize: config.pageSize
        };

        const tableInnerButtons = props.button
            .getButtons()
            .filter((item) => item.area === config.innerButtonArea)
            .map((item) => item.key);
        // meta[config.bodycode].items.push({
        //     label: this.state.multiLang['opr_title'],
        //     itemtype: 'customer',
        //     attrcode: 'opr',
        //     width: '140px',
        //     visible: true,
        //     fixed: 'right',
        //     render: (text, record, index) => {
        //         const spzt = _.get(record, 'spzt.value', '');
        //         const djzt = _.get(record, 'djzt.value', '');
        //         const red_status = _.get(record, 'red_status.value', '');
        //         const tradeType = _.get(record, 'djlxbm.value', '');

        //         return props.button.createOprationButton(
        //             tableInnerButtons.filter((item) => {
        //                 if (item === 'edit_table_inner' && (spzt !== '-1' || djzt === '-1')) {
        //                     return false;
        //                 } else if (item === 'submit_table_inner' && (spzt !== '-1' || djzt === '-1')) {
        //                     return false;
        //                 } else if (item === 'retrieve_table_inner' && !(djzt === '1' && spzt === '3')) {
        //                     return false;
        //                 } else if (item === 'delete_table_inner' && (spzt !== '-1' || djzt === '-1')) {
        //                     return false;
        //                 } else if (item === 'copy_table_inner' && (red_status === "1" || tradeType.startsWith('2647'))) {
        //                     return false
        //                 }
        //                 return true;
        //             }),
        //             // {
        //             //     area: config.innerButtonArea,
        //             //     buttonLimit: 3,
        //             //     onButtonClick: (props, key) => {
        //             //         onTableInnerButtonClick.call(this, props, key, text, record, index);
        //             //     }
        //             // }
        //         );
        //     }
        // });
        props.meta.setMeta(meta, () => {
            this.initPage();
        });
    }

    setButton(button) {
        const props = this.props;
        props.button.setButtons(button);

        // props.button.setPopContent({
        //     submit_table_inner: this.state.multiLang['confirm_submit_select'],
        //     retrieve_table_inner: this.state.multiLang['confirm_retrieve_select'],
        //     delete_table_inner: this.state.multiLang['confirm_delete_select']
        // });

    //    this.setInitButtonShow()
    }

    initPage() {
        const props = this.props;

        props.editTable.setTableData(config.bodycode, {rows: []}, (text, record) => {
            return (
                <a
                    // className="hyperlinks"
                    onClick={() => {
                        api.getIntellctfillQueryList({
                            openbillid: _.get(record, 'pk_jkbx.value'),
                            tradetype: _.get(record, 'djlxbm.value')
                        }).then((res) => {
                            if (!res || !res.url) {
                                toast({
                                    color: 'warning',
                                    content: this.state.multiLang['bad_request']
                                }); /* 国际化处理： 参数错误*/
                                return;
                            }
                            props.specialOpenTo(res.url, {
                                status: 'browse',
                                id: res.openbillid,
                                tradetype: res.tradetype,
                                appcode: res.appcode,
                                pagecode: res.pagecode,
                                scene: 'bz'
                            });
                        });
                    }}
                >
                    {_.get(record, 'djbh.value')}
                </a>
            );
        });
        this.setPageStatus();

        // props.search.setSearchValByField(config.headcode, 'djrq', {
        //     display: '今日~今日',
        //     value: '#day(0)#,#day(0)#'
        // });

        props.search.setDisabled(config.headcode,true);  // 设置查询区不可编辑  true 不可编辑 /false可以编辑

        // try {
        //    const searchVal = JSON.parse(getGlobalStorage('sessionStorage', config.searchCache));
        //    if (searchVal && searchVal.conditions) {
        //        this.props.search.setSearchValue(config.headcode, searchVal);
        //        this.loadData(searchVal, true);
        //    }
        // } catch (error) {
        //    console.log(error);
        // }

        // if (!getDefData('pk_org', config.dataSourceCommon)) {
        //     api.getUserInfo().then((data) => {
        //         setDefData('pk_org', config.dataSourceCommon, data.pk_org);
        //     });
        // }
    }

    setPageStatus(status = 'browse') { // 设置页面状态
        const props = this.props;
        props.setUrlParam({ status });
        // if (status === 'add') {
        //     props.form.setFormStatus(config.headcode, 'add');
        //     props.editTable.setStatus(config.bodycode, 'add');
        //     // props.button.setButtonDisabled(['edit', 'delete'], true);
        //     // props.button.setButtonDisabled(['temp_save', 'save', 'cancel', 'quickShare'], false);
        // } else 
        if (status === 'edit') {
            
            props.form.setFormStatus(config.headcode, 'edit');
            props.editTable.setStatus(config.bodycode, 'edit'); // 表体状态
            // 编辑态按钮： 导入  新增  删除  保存  取消
            props.button.setButtonVisible([
                'edit',
                'copy',
                'export', 
                'save',
                'enable',
                'disable',
            ], false)
            props.button.setButtonVisible([
                'import',
                'add', 
                'delete', 
                'save',
                'cancle'
            ], true)
            // this.handleImport()
            this.setState({
                orgDisabled:true
            })
        } else {
            props.form.setFormStatus(config.headcode, 'browse');
            props.editTable.setStatus(config.bodycode, 'browse');
            // 浏览态按钮： 修改 快速复制 导出 启用  停用
            props.button.setButtonVisible([
                'edit',
                'copy', 
                'export', 
                'enable', 
                'disable',
            ], true)

            props.button.setButtonVisible([
                'save',
                'add', 
                'delete', 
                'cancle',
                'import',
                
            ], false)

            this.setState({
                orgDisabled:false
            })

            // props.button.setButtonDisabled(['edit', 'delete'], false);
            // props.button.setButtonDisabled(['temp_save', 'save', 'cancel', 'quickShare'], true);
        }
    }

    save() { // 保存
        const props = this.props;
        // if (!this.checkValid()) return;
        let allData = props.editTable.getAllData(config.bodycode) || {};
        let rowsData = allData.rows && allData.rows.filter( item => item.status != '0') || [];
        const { currentOrg } = this.state;
        // 拼接入参
        let headData = {};
        headData.rows = rowsData;
        headData.areaType = "table";
        headData.areacode = "table";

        let reqData = {
            head:headData,
            appcode:config.appcode,
            pagecode:config.pagecode,
            pkOrg:currentOrg
            // userjson: "{'pk_tradetype':'" + pk_tradetype + "','pk_org':'" + pk_org + "','src':'" + src + "'}"
        }

        return api.saveBillData(reqData).then(data => {
            console.log('返回数据', data)
            this.handleResetOperateStatus()
            this.setPageStatus('browse');
            this.loadData('save');

        });
    }

    // checkValid() {
    //     const props = this.props;
    //     if (!props.form.isCheckNow(config.headcode)) {
    //         return;
    //     }
    //     if (!props.cardTable.checkTableRequired(config.bodycode)) {
    //         return;
    //     }
    //     const rows = props.cardTable.getVisibleRows(config.bodycode);
    //     const total = Number(props.form.getFormItemsValue(config.headcode, 'total').value);
    //     const input = rows.map(a => a.values.assume_amount.value).reduce((acc, cur) => Number(acc) + Number(cur), 0);
    //     if (total !== input) {
    //         toast({ color: 'warning', title: '报销金额不一致' }); /* 国际化处理： 请选择数据操作！*/
    //         return;
    //     }
    //     return true;
    // }
    
    handleInitQuickCopy(){ // 初始化快速复制
        if( !this.handleHasChooseOrg('quickcopy')){
            return 
        }
        let that = this;
        // 清空组织选择
        that.props.form.setFormItemsValue(config.quickcopycode, {'pk_org':{display: null, value: null}}) // 快速注册区域业务单元置空
        
        this.props.createUIDom(
            {
                pagecode: config.pagecode,//页面编码
                appcode: config.appcode//小应用编码
            },
            function (data) {
                let meta = that.props.meta.getMeta();
                meta[config.quickcopycode] = data.template[config.quickcopycode];
                meta[config.quickcopycode].items.find((item) => {
                    delete item.width;
                    if (item.attrcode === "pk_org") {
                        item.queryCondition = () => {
                            return {
                                // 筛选条件要管后台要
                                TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.BusinessUnitTreeRefBuilder',
                                appcode: that.props.getSearchParam('c')
                            };
    
                        }
                    }
                });
                that.props.meta.addMeta(meta);
                that.props.form.setFormStatus(config.quickcopycode, 'edit');
            })
        // that.setState({ quickcopypage: 'inner' });
        // that.setState({ showQuickCopyModal: true });
        that.handleShowOrHideQuickCopyModal(true)

    }

    handleShowOrHideQuickCopyModal(status){ // 快速复制弹框
        this.setState({
            showQuickCopyModal:status
        })
    }

    handleShowQuickCopyTip(){
        promptBox({
            color: 'warning', // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
            title: this.state.multiLang['common_title'], // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输
            content: this.state.multiLang['qucikCopy_tip'], // 提示内容,非必输
            beSureBtnName:this.state.multiLang['qucikCopy_sure'] , 
            cancelBtnName:this.state.multiLang['qucikCopy_cancle'] , 
            beSureBtnClick: this.handleQuickCopyBtnSure
        });
    }

    handleQuickCopyBtnSure(){ // 快速复制确定按钮事件 
        let data = this.props.form.getAllFormValue(config.quickcopycode); // 这里要获取当前选中的值
        if(data && data.rows && data.rows[0].values){
            let Ispk_orgnull = (data.rows[0].values.pk_org && data.rows[0].values.pk_org.value) == null || (data.rows[0].values.pk_org && data.rows[0].values.pk_org.value.length)===0;
            if(Ispk_orgnull){
                toast({ content: this.state.multiLang['check_pkorg'], color: 'warning' });//【业务单元】【交易类型】不能为空！
                return;
            }
        }

        // 获取查询区 pk_org
        // let currentOrg = this.props.search.getSearchValByField(config.headcode, 'pk_org').value.firstvalue;
        const { currentOrg='' } = this.state;
        let params = {};
        params.appcode = config.appcode;
        params.pagecode = config.pagecode;
        params.currentorg = currentOrg; // 当前业务单元 pk
        params.selectedorg = data.rows[0].values.pk_org.value // 当前选择的业务单元 pk

        this.setState({
            showQuickCopyModal:false
        }, () => {
            api.copyBillData(params).then( res => {
                toast({ content: this.state.multiLang['quickCopy_success'] , color: 'success' });
            })
        })
    }
    
    handleStartOrEndUse(status='enable'){ // 启停
        // if( !this.handleHasChooseOrg(status)){
        //     return 
        // }
        const props = this.props;
        const checkedRows = props.editTable.getCheckedRows(config.bodycode);
        console.log('checkedRows',checkedRows);
        let groupnos = []
        if(checkedRows.length>0 ){
            checkedRows.map( item => {
                let rowGroupno = item.data && item.data.values && item.data.values.groupno && item.data.values.groupno.value || '';
                rowGroupno && groupnos.push(rowGroupno);
            })
        }
        let params = {};
        
        params.appcode = config.appcode;
        params.pagecode = config.pagecode;
        params.groupnos = groupnos;
        params.ifStart = status==='enable' ? 'true' : 'false';

        if( checkedRows.length>=1 ){
            if( status==='disable'){
                api.startOrStopBillData(params).then( res => {  
                    this.loadData('disable')
                })
            }else{
                api.startOrStopBillData(params).then( res => {  
                    this.loadData('enable')
                })  
            }
        }

    } 

    handleExport(){ // 导出
        if( !this.handleHasChooseOrg('export')){
            return 
        }
        const { currentOrg } = this.state;
        let data = {
            "pkOrg": currentOrg,
            appcode:config.appcode,
            pagecode:config.pagecode
        }
        formDownload({
            params: data,
            url: '/nccloud/erm/ersetting/IntellectfillExportAction.do',
            enctype: 2
        })

    }

    handleImport(){ // 导入
        if( !this.handleHasChooseOrg()){ // 判断是否选择组织
            return
        }
        let that = this;
        let toastArr = [];
        const { currentOrg } = this.state;
        that.handleInitImport("erm", "2611", 0, currentOrg, (resultinfo) => {
            if (resultinfo == 'beginUpload') {
                toastArr.push(1);
            } else if (resultinfo.success) {
                toast({ 
                    content: that.state.multiLang["toast_import_success"], 
                    color: 'success' 
                });//'导入成功'
                let olddata = that.props.editTable.getAllData(config.bodycode).rows;
                let len = 0;
                olddata.find((row) => {
                    if (row.status == 0) {
                        len++;
                    }
                })
                let exceldata = resultinfo.data[config.bodycode];
                // 回写数据
                exceldata.rows.find((row) => {
                    that.props.editTable.addRow(config.bodycode, len, false, row.values); // false 不自动聚焦
                    len++;
                });
                this.setState({
                    isHasImport:true
                })
            }
        });

    }

    handleInitImport(moduleName,billType, importSign, pk_org, callback){ // 初始化导入按钮

        let previousStatus;
        let excelimportconfig = {
            name: 'file',
            showUploadList: false,
            action: '/nccloud/erm/ersetting/IntellectfillImportAction.do',
            headers: {
                authorization: 'authorization-text'
            }
        };
        let resultStr = ''
    
        let  data = {
            moduleName:moduleName,
            billType:billType,
            importSign: importSign,
            pk_org: pk_org,
        };
        excelimportconfig.data = data;
        excelimportconfig.NcUploadOnChange = (info) => {
            // const gziptools = new Gzip();
            // let response = typeof info.file.response == 'string' ? gziptools.unzip(info.file.response): info.file.response; 
            let response = info.file.response;
            if(info.file.status == 'uploading' && info.file.status != previousStatus) {
                callback('beginUpload');
                previousStatus = 'uploading';
            }
            
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                //记录成功或失败信息
                if(response.error){
                    if(response.error.message){
                        toast({ 
                            content: response.error.message, 
                            color: 'warning' 
                        });
                        return
                        // callback(response.error.message);
                        // resultStr = response.error.message;
                    }
                }
                //记录成功或失败信息
                if(response.success){
                    callback(response);
            }
                console.log(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                console.log(`${info.file.name} file upload failed.`);
        }
    };
    this.props.button.setUploadConfig('import', excelimportconfig); // 设置导入按钮功能
  
    }

    handleDelete(){ // 删除确定按钮
        const props = this.props;
        let data = props.editTable.getCheckedRows(config.bodycode) || [];
        let arr = data.map(item => item.index);
        props.editTable.deleteTableRowsByIndex(config.bodycode, arr);
        toast({ content: this.state.multiLang["toast_delete_success"], color: 'success' });//'删除成功'
        this.setState({
            isHasDelete:true
        })
    }

    handleShowOrHideDeleteModal(){ // 删除弹框显示
        const props = this.props;
        let data = props.editTable.getCheckedRows(config.bodycode) || [];
        if (data.length > 0) {
            let isHasEmpty = false; // 判断是否有新增数据删除
            let haveDisable = data.every( item => { 
                let tempItem = _.get(item,'data.values.qyzt.value', "");
                if( tempItem === '' ){
                    isHasEmpty = true
                }
                return tempItem === '0'
            })
            if( !isHasEmpty && !haveDisable ){ // 只有所有的状态不是停用的时候还能删除
                promptBox({
                    color: 'warning', // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                    title: this.state.multiLang['prompt_title'], // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输
                    content: this.state.multiLang['have_enable_data'], // 提示内容,非必输
                    beSureBtnName:this.state.multiLang['qucikCopy_sure'] ,
                    noCancelBtn:true
                });
                return;
            }else{
                promptBox({
                    color: 'warning', // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                    title: this.state.multiLang['prompt_title'], // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输
                    content: this.state.multiLang['confirm_delete_select'], // 提示内容,非必输
                    beSureBtnName:this.state.multiLang['qucikCopy_sure'] , 
                    cancelBtnName:this.state.multiLang['qucikCopy_cancle'] , 
                    beSureBtnClick:() => this.handleDelete()
                });
                return;
            }
        }

    }

    addTableLine(){ // 增行
        if( !this.handleHasChooseOrg('add')){
            return 
        }
        const props = this.props;
        props.editTable.addRow(config.bodycode, -1, true);
        this.setState({
            isHasAdd:true
        })
    }

    loadData(isFromSearch) {
        if( !this.handleHasChooseOrg()){ // 判断是否选择组织
            return
        }
        const props = this.props;
        const meta = props.meta.getMeta();
        const pageInfo = props.editTable.getTablePageInfo(config.bodycode) || {};

        const query = props.search.getAllSearchData(config.headcode);
        const { currentOrg } = this.state;

        let currentPageSize = config.pageSize;
        const { isInitPageSize } = this.state;
        if( !isInitPageSize ){ // 查询或者切换分页
            if( 100 !== pageInfo.pageSize){ // 如果选择过分页，使用当前选择的分页数据
                currentPageSize = pageInfo.pageSize;
            }
        }else{
            this.setState({
                isInitPageSize:false
            })      
        }
        
        const params = {
            src:'org',
            appcode: config.appcode,
            pagecode: config.pagecode,
            groupOrOrg:currentOrg,
            queryAreaCode: config.headcode,
            querytype: 'tree',
            querycondition: query,
            oid: meta[config.headcode].oid,
            pageInfo: {
                pageIndex: isFromSearch !== 'init' ? pageInfo.pageIndex : 0, // 点击查询重置分页
                pageSize: currentPageSize
            }
        };

        return api.getIntellctfillQueryList(params).then((res) => {
            if( res ){ // 判断是否有数据
                if (isFromSearch) {
                    const total = Number(_.get(res, 'pageInfo.total', 0));
                    if (total === 0) {
                        toast({
                            color: 'warning',
                            content: this.state.multiLang['query_none_message']
                        }); /* 国际化处理： 未查询出符合条件的数据*/
                    } else {
                        if( 
                            isFromSearch === 'disable'  || 
                            isFromSearch === 'enable' ||
                            isFromSearch === 'save' || 
                            isFromSearch === 'cancle' 
                        ){ // 启用、停用、保存提示语
                            let content = this.state.multiLang[`${isFromSearch}_success`];
                            toast({ content: content, color: 'success' });
                        }else if('init' === isFromSearch ){
                            toast({
                                color: 'success',
                                content: this.state.multiLang['query_total_message'].replace('{count}', total)
                            }); /* 国际化处理： 查询成功，共*条*/
                        }

                    }
                } else {
                    // toast({
                    //     color: 'success',
                    //     content: this.state.multiLang['query_success']
                    // }); /* 国际化处理： 查询成功*/
                }
            
                this.setData(res);
            }
            else{ // 没有数据清空表体数据
            //     toast({ content: this.state.multiLang['search_no_data'], color: 'success' });
                this.props.editTable.setTableData(config.bodycode, {rows: []});
            }
        });
    }

    setData(res) {
        const props = this.props;
        const pageInfo = _.get(res, `pageInfo`, {});

        let rowsData = _.get(res, `data.${config.bodycode}.rows`, [])
        const data = {
            rows: rowsData, // 这里注意取值
            pageInfo: pageInfo
        };
        if (pageInfo.pageIndex == 0) { // 初始化分页
            data.allpks = new Array(Number(pageInfo.total));
        }
        // debugger
        props.editTable.setTableData(config.bodycode, data);

        // 根据启用状态判断当前行是否可用 
        // rowsData.map( (item, index) => {
        //     let qyzt = _.get(item,'values.qyzt.value', "1")
        //     let status = qyzt === '1'
        //     props.editTable.setEditableRowByIndex(config.bodycode, index, status)
        // })
    }

    handleCancle(){
        const { isHasDelete, isHasAdd, isHasImport } = this.state
        if( isHasDelete || isHasAdd || isHasImport){ // 如果当前页面执行了删除没有保存，弹框提示
            promptBox({
                color: 'warning', // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                title: this.state.multiLang['prompt_title'], // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输
                content: this.state.multiLang['cancle_confirm'], // 提示内容,非必输
                beSureBtnName:this.state.multiLang['qucikCopy_sure'] , 
                cancelBtnName:this.state.multiLang['qucikCopy_cancle'] , 
                beSureBtnClick:() => this.handleCancleBtnSure()
            });
            return;
        }else{
            // this.setPageStatus('browse') 
            // this.load
            this.handleCancleBtnSure()
        }
    }

    handleCancleBtnSure(){
        this.setPageStatus('browse')
        this.handleResetOperateStatus()
        this.loadData('cancle')
    }

    handleResetOperateStatus(){ // 重置操作状态
        this.setState({
            isHasAdd:false,
            isHasDelete:false,
            isHasImport:false
        })
    }

    onBusinessUnitTreeRefChange(data) {
        console.log('data',data);
        if (!data || !data.refpk) { // 清空业务单元
            this.setState({ 
                pk_org: '',
                currentOrg:'',
                businessUnitTreeRefValue : {},
            })
            this.props.search.setDisabled(config.headcode,true);  // 设置查询区编辑状态  true 不可编辑 /false可以编辑
            return;
        }
        let that = this
        this.setState({ 
            pk_org: data,
            currentOrg:data.refpk || '',
            businessUnitTreeRefValue : data,
        },() => {
            that.handleImport() // 重新调用一次，要不导入点击一次不出现弹框
            // that.props.search.setSearchValByField(config.headcode, 'pk_dept', { display: '', value: '' }); // 查询区 部门置空
            that.props.form.setFormItemsValue(config.quickcopycode, {'pk_org':{display: null, value: null}}) // 快速注册区域业务单元置空
            // 获取所有查询区域字段，清空数据
            let searchData = that.props.search.getAllSearchData(config.headcode, false) || [];
            searchData.conditions.map( item => {
                that.props.search.setSearchValByField(config.headcode, item.field, { display: '', value: '' }); // 查询区 部门置空
            })
            // 重新查询数据
            this.loadData('reSearch');

            this.props.search.setDisabled(config.headcode,false);  // 设置查询区编辑状态  true 不可编辑 /false可以编辑
        });
    }

    handleHasChooseOrg(operate='common'){ // 判断是否选择组织
        const { currentOrg='' } = this.state;
        let content = this.state.multiLang[`${operate}_no_org`];
        if( !currentOrg ){
            toast({ content: content, color: 'warning' });
            return false
        }
        return true
    }

    handleEdit(){ 
        if( !this.handleHasChooseOrg() ){ // 修改增加选择组织判断
            return
        }
        this.setPageStatus('edit')
    }


    render() {
        const { table, button, search, modal, BillHeadInfo, editTable, form } = this.props;
        const { NCCreateSearch } = search;
        const { createBillHeadInfo } = BillHeadInfo;
        const { createEditTable } = editTable;
        const { createForm } = form;
        let { createModal } = modal;
        // let totalPage =  Math.floor(this.state.total/config.pageSize);
        return (
            <div className="nc-single-table">
                <div className="nc-singleTable-header-area">
                    <div className="header-title-search-area" style={{display:'flex',alignItems:'center'}}>
                        {createBillHeadInfo({
                            title: this.state.multiLang['org_page_title'],
                            initShowBackBtn: false
                        })}
                        <div className="business-unit-tree-ref" >
                            <span className="mustFillIn_search1 iconfont icon-xinghao"></span>
                            <BusinessUnitTreeRef
                                value={this.state.pk_org || ''}
                                disabled={this.state.orgDisabled}
                                onChange={this.onBusinessUnitTreeRefChange.bind(this)}
                                queryCondition={() => {
                                    return {
                                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.BusinessUnitTreeRefBuilder',
                                        appcode: config.appcode,
                                        DataPowerOperationCode: 'fi',
                                        isDataPowerEnable: 'Y'
                                    };
                                }}
                            />
                        </div>
                    </div>
                    <div className="header-button-area">
                        {button.createButtonApp({
                            area: config.pageButtonArea,
                            buttonLimit: 8,
                            onButtonClick: onPageButtonClick.bind(this)
                        })}
                    </div>
                </div>
                <div className="nc-singleTable-search-area">
                    {NCCreateSearch(config.headcode, { clickSearchBtn: onSearchButtonClick.bind(this) })}
                </div>
                <div className="nc-singleTable-table-area">
                    {createEditTable(config.bodycode, {
                        handlePageInfoChange: onTablePageChange.bind(this),
                        selectedChange: onTableSelectChange.bind(this),
                        showIndex: true,
                        showCheck: true,
                        showPagination:true
                    })}
                </div>

                {/* 导入 modal */}
                {createModal('importModal', {
                    noFooter : true, 
                    className: 'import-modal'
                })}

                {/*快速复制*/}
                <NCModal
                    dialogClassName='copy-to'
                    backdrop='static'
                    show={
                        this.state.showQuickCopyModal
                    } 
                    size='sm'
                    onHide={() => this.handleShowOrHideQuickCopyModal(false)}>
                    <NCModal.Header closeButton="true">
                        <NCModal.Title>{this.state.multiLang['qucikCopy_title']}</NCModal.Title>
                    </NCModal.Header>
                    <NCModal.Body>
                        <div className="form-wrapper">
                            {createForm(`${config.quickcopycode}`,{
                                // onAfterEvent: this.handleQuickCopyBtnSure()
                                onAfterEvent: this.handleShowQuickCopyTip
                            })}
                        </div>
                    </NCModal.Body>
                    <NCModal.Footer>

                        <NCButton colors='primary' onClick={() => this.handleShowQuickCopyTip()}>
                            {this.state.multiLang['qucikCopy_sure']}
                        </NCButton>
                        <NCButton onClick={() => this.handleShowOrHideQuickCopyModal(false)}>
                            {this.state.multiLang['qucikCopy_cancle']}
                        </NCButton>
                    </NCModal.Footer>
                </NCModal>

                {/* <div className="box">
                    <NCPagination
                        prev
                        next
                        maxButtons={3}
                        // boundaryLinks
                        activePage={this.state.activePage}
                        onSelect={this.handlePaginationSelect.bind(this)}
                        // onDataNumSelect={this.dataNumSelect}
                        total={this.state.total}
                        // dataNum={1}
                        items={ totalPage }
                    />

                </div> */}
            </div>
        );
    }
}

export default createPage({
    // billinfo: {
    //     billtype: 'grid',
    //     pagecode: config.pagecode,
    //     headcode: config.headcode
    // },
    mutiLangCode: config.mutiLangCode,
    initTemplate: null
})(Page);
